<template>
  <div class="shipping-detail-container">
    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-item">
        <label>关键词</label>
        <input type="text" placeholder="请输入发货单号/产品名称/产品编号" v-model="query.keyword">
      </div>
      <div class="filter-item">
        <label>发货时间</label>
        <input type="text" placeholder="请选择创建时间" v-model="query.time">
      </div>
      <div class="filter-buttons">
        <button class="btn-primary" @click="onSearch">搜索</button>
        <button class="btn-secondary" @click="onReset">重置</button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <table>
        <thead>
          <tr>
            <th><input type="checkbox" v-model="allSelected"></th>
            <th>发货单号</th>
            <th>发货状态</th>
            <th>发货产品</th>
            <th>规格</th>
            <th>分类</th>
            <th>单位</th>
            <th>发货数量</th>
            <th>发货时间</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in details" :key="index">
            <td><input type="checkbox" v-model="item.selected"></td>
            <td>
              <a href="javascript:void(0)" @click="viewDeliveryDetail(item)" class="delivery-link">
                {{ item.shipmentNo }}
              </a>
            </td>
            <td><span :class="statusClass(item.status)">{{ item.status }}</span></td>
            <td>{{ item.productName }} <span class="product-code">{{ item.productCode }}</span></td>
            <td>{{ item.spec }}</td>
            <td>{{ item.category }}</td>
            <td>{{ item.unit }}</td>
            <td>{{ item.quantity }}</td>
            <td>{{ item.shipTime }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 底部区域 -->
    <div class="footer-section">
      <div class="footer-left">
        <input type="checkbox" v-model="allSelected">
        <label>全选</label>
        <button class="btn-secondary">导出</button>
      </div>
      <div class="pagination">
        <button @click="changePage(page.pageNum - 1)" :disabled="page.pageNum <= 1">&lt;</button>
        <button 
          v-for="pageNum in getPageNumbers()" 
          :key="pageNum"
          :class="{ active: pageNum === page.pageNum }"
          @click="changePage(pageNum)"
        >
          {{ pageNum }}
        </button>
        <button @click="changePage(page.pageNum + 1)" :disabled="page.pageNum >= page.pages">&gt;</button>
        <select v-model="page.pageSize" @change="onPageSizeChange">
          <option value="5">5条/页</option>
          <option value="10">10条/页</option>
          <option value="20">20条/页</option>
          <option value="50">50条/页</option>
        </select>
        <span class="page-info">共 {{ page.total }} 条记录</span>
      </div>
    </div>

    <!-- 发货单详情抽屉 -->
    <div v-if="showDetailModal" class="drawer-overlay" @click="closeDetailModal">
      <div class="drawer-content" @click.stop>
        <div class="drawer-header">
          <h3>发货单详情</h3>
          <button class="close-btn" @click="closeDetailModal">&times;</button>
        </div>
        <div class="drawer-body" v-if="deliveryDetail">
          <div class="detail-section">
            <h4>基本信息</h4>
            <div class="detail-list">
              <div class="detail-item">
                <label>发货单号：</label>
                <span>{{ deliveryDetail.deliveryOrderNo }}</span>
              </div>
              <div class="detail-item">
                <label>审批状态：</label>
                <span :class="approvalStatusClass(deliveryDetail.approvalStatus)">
                  {{ getApprovalStatusText(deliveryDetail.approvalStatus) }}
                </span>
              </div>
              <div class="detail-item">
                <label>申请时间：</label>
                <span>{{ formatDate(deliveryDetail.applyTime) }}</span>
              </div>
              <div class="detail-item">
                <label>期望发货时间：</label>
                <span>{{ formatDate(deliveryDetail.expectedDeliveryDate) }}</span>
              </div>
              <div class="detail-item">
                <label>出库状态：</label>
                <span :class="outboundStatusClass(deliveryDetail.outboundStatus)">
                  {{ getOutboundStatusText(deliveryDetail.outboundStatus) }}
                </span>
              </div>
            </div>
          </div>
        </div>
        <div class="drawer-footer">
          <button class="btn-secondary" @click="closeDetailModal">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { deliveryDetailPage, deliveryDetail } from '@/api/sale/delivery'

export default {
  name: 'ShippingDetail',
  data() {
    return {
      query: { keyword: '', time: '' },
      page: { pageNum: 1, pageSize: 5, total: 0, pages: 0 },
      details: [],
      showDetailModal: false,
      deliveryDetail: null
    };
  },
  computed: {
    allSelected: {
      get() {
        return this.details.length > 0 && this.details.every(item => item.selected);
      },
      set(value) {
        this.details.forEach(item => {
          item.selected = value;
        });
      }
    }
  },
  created() {
    this.fetch()
  },
  methods: {
    async fetch() {
      const body = {
        pageNum: this.page.pageNum,
        pageSize: this.page.pageSize,
        productName: this.query.keyword || undefined
      }
      const res = await deliveryDetailPage(body)
      const payload = res?.data || res
      const data = payload?.data || payload
      const records = data?.records || []
      
      // 更新分页信息
      this.page.total = data?.total || 0
      this.page.pages = data?.pages || 0
      
      // 将后端字段映射到现有表格字段（尽量兼容实际返回字段名）
      this.details = records.map(r => ({
        selected: false,
        shipmentNo: r.deliveryOrderNo || r.deliveryOrderId || '-',
        deliveryOrderId: r.deliveryOrderId, // 保存发货单ID用于详情查询
        status: r.outboundStatusText || r.status || '-',
        productName: r.productName || '-',
        productCode: r.productCode || '-',
        spec: r.specification || r.spec || '-',
        category: r.category || '-',
        unit: r.unitName || r.unit || '-',
        quantity: r.quantity || r.amount || 0,
        shipTime: r.shipTime || r.productionDate || '-'
      }))
    },
    onSearch() {
      this.page.pageNum = 1
      this.fetch()
    },
    onReset() {
      this.query = { keyword: '', time: '' }
      this.page.pageNum = 1
      this.fetch()
    },
    changePage(p) {
      if (p < 1 || p > this.page.pages) return
      this.page.pageNum = p
      this.fetch()
    },
    onPageSizeChange() {
      this.page.pageNum = 1
      this.fetch()
    },
    getPageNumbers() {
      const current = this.page.pageNum
      const total = this.page.pages
      const pages = []
      
      if (total <= 7) {
        // 总页数少于等于7页，显示所有页码
        for (let i = 1; i <= total; i++) {
          pages.push(i)
        }
      } else {
        // 总页数大于7页，显示省略号
        if (current <= 4) {
          // 当前页在前4页
          for (let i = 1; i <= 5; i++) {
            pages.push(i)
          }
          pages.push('...')
          pages.push(total)
        } else if (current >= total - 3) {
          // 当前页在后4页
          pages.push(1)
          pages.push('...')
          for (let i = total - 4; i <= total; i++) {
            pages.push(i)
          }
        } else {
          // 当前页在中间
          pages.push(1)
          pages.push('...')
          for (let i = current - 1; i <= current + 1; i++) {
            pages.push(i)
          }
          pages.push('...')
          pages.push(total)
        }
      }
      
      return pages
    },
    statusClass(status) {
      if (status === '未发货') return 'status-pending';
      if (status === '部分发货') return 'status-partial';
      if (status === '已发货' || status === '已完成') return 'status-shipped';
      return '';
    },
    async viewDeliveryDetail(item) {
      try {
        // 从发货明细中获取发货单ID
        const deliveryOrderId = item.deliveryOrderId || item.deliveryOrderNo;
        if (!deliveryOrderId) {
          this.$message.error('无法获取发货单ID');
          return;
        }
        
        // 调用发货单详情API
        const res = await deliveryDetail(deliveryOrderId);
        const payload = res?.data || res;
        this.deliveryDetail = payload?.data || payload;
        this.showDetailModal = true;
      } catch (error) {
        console.error('获取发货单详情失败:', error);
        this.$message.error('获取发货单详情失败');
      }
    },
    closeDetailModal() {
      this.showDetailModal = false;
      this.deliveryDetail = null;
    },
    getApprovalStatusText(status) {
      const statusMap = {
        0: '审核通过',
        1: '待审核', 
        2: '审核驳回'
      };
      return statusMap[status] || '未知';
    },
    getOutboundStatusText(status) {
      const statusMap = {
        0: '全部出库',
        1: '部分出库',
        2: '未出库'
      };
      return statusMap[status] || '未知';
    },
    approvalStatusClass(status) {
      if (status === 0) return 'status-approved';
      if (status === 1) return 'status-pending';
      if (status === 2) return 'status-rejected';
      return '';
    },
    outboundStatusClass(status) {
      if (status === 0) return 'status-shipped';
      if (status === 1) return 'status-partial';
      if (status === 2) return 'status-pending';
      return '';
    },
    formatDate(date) {
      if (!date) return '-';
      return new Date(date).toLocaleString('zh-CN');
    }
  }
}
</script>

<style scoped>
.shipping-detail-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.filter-section {
  display: flex;
  gap: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-size: 14px;
}

.filter-item input {
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 260px;
}

.filter-buttons {
  margin-left: auto;
}

.btn-primary {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-secondary {
  background-color: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px;
}

.table-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

th {
  background-color: #f8f9fa;
}

.product-code {
  color: #909399;
  font-size: 12px;
  margin-left: 5px;
}

.status-pending { color: #67c23a; }
.status-partial { color: #e6a23c; }
.status-shipped { color: #f56c6c; }
.status-completed { color: #909399; }

.footer-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  background-color: #fff;
  padding: 10px 20px;
  border-radius: 8px;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination button {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  cursor: pointer;
  border-radius: 4px;
}

.pagination button.active {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.pagination button:disabled {
  background-color: #f5f7fa;
  color: #c0c4cc;
  border-color: #e4e7ed;
  cursor: not-allowed;
}

.pagination select {
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-left: 10px;
}

.page-info {
  margin-left: 10px;
  color: #606266;
  font-size: 14px;
}

/* 发货单号链接样式 */
.delivery-link {
  color: #409eff;
  text-decoration: none;
  cursor: pointer;
}

.delivery-link:hover {
  color: #66b1ff;
  text-decoration: underline;
}

/* 抽屉样式 */
.drawer-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  animation: fadeIn 0.3s ease-out;
}

.drawer-content {
  position: fixed;
  top: 0;
  right: 0;
  width: 400px;
  height: 100%;
  background: white;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  animation: slideInRight 0.3s ease-out;
}

.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  background: #f8f9fa;
}

.drawer-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #909399;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.2s;
}

.close-btn:hover {
  color: #409eff;
  background: #f0f9ff;
}

.drawer-body {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.detail-section h4 {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
}

.detail-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.detail-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.detail-item:last-child {
  border-bottom: none;
}

.detail-item label {
  font-weight: 500;
  color: #606266;
  margin-right: 12px;
  min-width: 100px;
  flex-shrink: 0;
}

.detail-item span {
  color: #303133;
  flex: 1;
  word-break: break-all;
}

.drawer-footer {
  padding: 20px;
  border-top: 1px solid #ebeef5;
  text-align: right;
  background: #f8f9fa;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideInRight {
  from {
    transform: translateX(100%);
  }
  to {
    transform: translateX(0);
  }
}

/* 状态样式 */
.status-approved { color: #67c23a; }
.status-pending { color: #e6a23c; }
.status-rejected { color: #f56c6c; }
.status-shipped { color: #67c23a; }
.status-partial { color: #e6a23c; }
</style>
